#!/usr/bin/env bash
#

UUID=`blkid -s UUID -o value /dev/${partition3}`  # Узнать UUID корневого диска
#-------
while true; do
    echo -en "----------------------------------------------------------------------\n"
    echo -en "| Выберите загрузчик\n"
    echo -en "| Оставьте поле пустым для выбора по умолчанию: SYSTEMD-BOOT\n"
    echo -en "----------------------------------------------------------------------\n"
    echo -en "| 1 - GRUB\n| 2 - SYSTEMD-BOOT\n"
    read -r -p "| Ваш выбор (1/2): >>> " boot_type
    case ${boot_type} in
        1)
			echo "| Ваш выбор - GRUB"
			pacstrap -K /mnt grub --noconfirm
			arch-chroot /mnt /bin/bash -c "grub-install --efi-directory=/efi --boot-directory=/boot --bootloader-id=\"Linux Boot Manager\""
			arch-chroot /mnt /bin/bash -c "grub-mkconfig -o /boot/grub/grub.cfg"
			break;;
        2 | "")
			echo "| Ваш выбор - SYSTEMD-BOOT"
			arch-chroot /mnt /bin/bash -c "bootctl --esp-path=/efi --boot-path=/boot install --efi-boot-option-description=\"Linux Boot Manager\""
			{
				echo "default arch.conf"
				echo "timeout menu-force"
				echo "console-mode auto"
				echo "editor no"
			} >>/mnt/efi/loader/loader.conf
			#-------
			{
				echo "title    Arch Linux"
				echo "linux    /vmlinuz-linux"
				echo "initrd    /${proc_ucode}.img"
				echo "initrd    /initramfs-linux.img"
			} >>/mnt/boot/loader/entries/arch.conf
			#-------
			{
				echo "title    Arch Linux fallback"
				echo "linux    /vmlinuz-linux"
				echo "initrd    /${proc_ucode}.img"
				echo "initrd    /initramfs-linux-fallback.img"
			} >>/mnt/boot/loader/entries/arch-fb.conf
			#-------
			if [[ "${fs_type}" = "1" ]]; then
				echo "options    rw root=\"UUID=${UUID}\" quiet splash loglevel=3 nowatchdog raid=noautodetect rootfstype=btrfs rootflags=subvol=@" >> /mnt/boot/loader/entries/arch.conf
				echo "options    rw root=\"UUID=${UUID}\" quiet splash loglevel=3 nowatchdog raid=noautodetect rootfstype=btrfs rootflags=subvol=@" >> /mnt/boot/loader/entries/arch-fb.conf
			else
				echo "options    rw root=\"UUID=${UUID}\" quiet splash loglevel=3 nowatchdog raid=noautodetect rootfstype=ext4" >> /mnt/boot/loader/entries/arch.conf
				echo "options    rw root=\"UUID=${UUID}\" quiet splash loglevel=3 nowatchdog raid=noautodetect rootfstype=ext4" >> /mnt/boot/loader/entries/arch-fb.conf
			fi
			#-------
			if grep -E "NVIDIA|GeForce" <<< ${gpu_type}; then
				sed -i '/^options/s/$/ nvidia_drm.modeset=1/' /mnt/boot/loader/entries/arch.conf
				sed -i '/^options/s/$/ nvidia_drm.modeset=1/' /mnt/boot/loader/entries/arch-fb.conf
				sed -i '/^MODULES/s/\(.\)$/nvidia nvidia_modeset nvidia_uvm nvidia_drm)/' /mnt/etc/mkinitcpio.conf
			fi
			break;;
        *)
			echo "| Неверный ввод, попробуйте снова..."
			continue;;
    esac
done
echo "| Загрузчик установлен и настроен..."
